<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF - 8">
    <meta name="viewport" content="width=device - width, initial - scale = 1.0">
    <title>离线填报数据缓存与上传</title>
    <link rel="icon" href="https://repair.qiantaolu.com/exam-api/static_pc/1896476650888691713.png">

</head>

<body>
    <form id="form">
        <label for="name">姓名:</label>
        <input type="text" id="name" name="name" required><br><br>
        <label for="email">邮箱:</label>
        <input type="password" id="email" name="email" required><br><br>

        <label for="file">文件:</label>
        <input type="file" id="file" name="file" required><br><br>

        <input type="submit" value="提交">
    </form>
    <button onclick="getDataFromDB()">查看</button>
    <script>
        // 打开或创建IndexedDB数据库
        function openDB() {
            return new Promise((resolve, reject) => {
                const request = window.indexedDB.open('offlineFormDB', 1);
                request.onsuccess = (event) => {
                    resolve(event.target.result);
                };
                request.onupgradeneeded = (event) => {
                    const db = event.target.result;
                    db.createObjectStore('formData', { keyPath: 'id', autoIncrement: true });
                };
                request.onerror = (event) => {
                    reject(event.target.error);
                };
            });
        }

        // 保存数据到IndexedDB
        async function saveDataToDB(data) {
            const db = await openDB();
            const transaction = db.transaction(['formData'],'readwrite');
            const objectStore = transaction.objectStore('formData');
            objectStore.add(data);
        }

        // 从IndexedDB获取所有数据
        async function getDataFromDB() {
            const db = await openDB();
            const transaction = db.transaction(['formData'],'readonly');
            const objectStore = transaction.objectStore('formData');
            return await new Promise((resolve, reject) => {
                const request = objectStore.getAll();
                request.onsuccess = (event) => {
                    resolve(event.target.result);
                    console.log(event.target.result);
                };
                request.onerror = (event) => {
                    reject(event.target.error);
                };
            });
        }

        // 上传数据到服务器
        async function uploadData(data) {
            try {
                const response = await fetch('your - server - endpoint', {
                    method: 'POST',
                    headers: {
                        'Content - Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });
                if (response.ok) {
                    return true;
                } else {
                    return false;
                }
            } catch (error) {
                return false;
            }
        }

        // 监听表单提交事件
        document.getElementById('form').addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = {};
            const elements = e.target.elements;
            for (let i = 0; i < elements.length; i++) {
                if (elements[i].name) {
                    formData[elements[i].name] = elements[i].value;
                }
            }
            console.log(window.navigator);
            if (window.navigator.onLine) {
                const success = await uploadData(formData);
                if (success) {
                    console.log('数据已成功上传');
                } else {
                    await saveDataToDB(formData);
                    console.log('上传失败，数据已缓存');
                }
            } else {
                await saveDataToDB(formData);
                console.log('无网络，数据已缓存');
            }
        });

        // 监听网络状态变化
        window.addEventListener('online', async () => {
            const data = await getDataFromDB();
            for (let i = 0; i < data.length; i++) {
                const success = await uploadData(data[i]);
                if (success) {
                    // 如果上传成功，从IndexedDB中删除数据
                    const db = await openDB();
                    const transaction = db.transaction(['formData'],'readwrite');
                    const objectStore = transaction.objectStore('formData');
                    objectStore.delete(data[i].id);
                    console.log('缓存数据已成功上传并删除');
                } else {
                    console.log('缓存数据上传失败');
                }
            }
        });
    </script>
</body>

</html>